function tst = megTestOneVsRest(R,T,varargin)
% input: R - structure from train function
%        T - testdata trialsXfeatures,
%        L - Labels (arbitrary)
%        optional: featselect - your featureselction method                    
%                   balance - balance trainset (default:false)

param = args2Param(varargin);

nClasses = length(R.classes);
tst.distW = zeros(size(T,1),nClasses);
for k=1:nClasses;
    if isfield(param,'featselect') && ~strcmpi(param.featselect,'none'),
        % do feature selection
        if strcmpi(param.featselect,'CSP'),
            Treshaped = reshape(T',[param.reshape.reSize,size(T,1)]);
            [varDat,filtDat ]=megCSPApply(Treshaped,R.csp{k}.W,param.nSpatialFilter);
            if strcmpi(param.cspFeat, 'filter'),
                curT = megReshapeTrain(filtDat,true,R.csp{k}.reshapeParam);
            else
                curT=megReshapeTrain(varDat,1,R.csp{k}.reshapeParam);
            end            
        else
            curT = T(:,R.feat_bin{k});
        end
    else
        curT=T;
    end
    % get distance to hyperplane; if distW>0, first class predicted else
    % 2nd class of classPair predicted
    tst.distW(:,k) = getWDist(curT',R.W{k},R.b0(k));
end

if strcmpi(param.validationMethod,'max'), % maximum distance winner    
    [dummy maxIdx]=max(tst.distW,[],2);
    tst.prediction = R.classes(maxIdx);
end

% function distW=getWDist(dat,W,b0)
% % get distance to hyperplane
% 
% x_dot_w = dat' * (W'*ones(1,size(dat,2)));
% x_dot_w = (x_dot_w .* eye(size(dat,2))) * ones(size(dat,2),1);
% distW = (x_dot_w + b0) / norm(W);

function param = args2Param(args)

% set default values
param.validationMethod = 'max';

k=1;
while k<length(args),
    if ischar(args{k}),
        if strcmpi('param',args{k}),
            tmp=args{k+1};
            fNames=fieldnames(tmp);
            for p=1:length(fNames),
                eval(['param.' fNames{p} '=tmp.' fNames{p} ';'] );
            end
        end
        if strcmpi('validation',args{k}),
            param.validationMethod=args{k+1};
        end
        if strcmpi('featselect',args{k}),
            param.featselect=args{k+1};
        end
    else
        error('argument name must be a string');
    end
    k=k+2;
end
